<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item> 任务管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-input
          placeholder="任务名称"
          class="mr10 handle-input"
          size="medium"
          v-model="search.taskName"
        ></el-input>
        <el-button
          class="mr10 ml10"
          type="primary"
          size="medium"
          icon="el-icon-search"
          @click="currentChange"
          >搜索</el-button
        >
        <el-button
          class="mr10"
          icon="el-icon-refresh"
          size="medium"
          @click="refresh"
          >刷新</el-button
        >
        <el-button size="medium" class="mr10" @click="dialogAdd = true"
          ><i class="el-icon-circle-plus-outline"></i> 添加新任务</el-button
        >
        <el-popconfirm
          title="确定启用吗？"
          @confirm="handlerEnabledTask()"
          class="ml10"
        >
          <el-button size="medium" class="mr10" slot="reference"
            >批量启用</el-button
          >
        </el-popconfirm>
        <el-popconfirm
          title="确定禁用吗？"
          @confirm="handlerDisabledTask()"
          class="ml10"
        >
          <el-button size="medium" class="mr10" type="danger" slot="reference"
            >批量禁用</el-button
          >
        </el-popconfirm>
        <el-popconfirm
          title="确定删除吗？"
          @confirm="handlerBatchDeleteTask()"
          class="ml10"
        >
          <el-button type="danger" size="medium" slot="reference"
            ><i class="el-icon-delete"></i> 批量删除</el-button
          >
        </el-popconfirm>
      </div>

      <el-table
        ref="multipleTable"
        :loading="loading"
        :data="page.records"
        style="width: 100%"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
        ><el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="taskId" label="任务ID" sortable="custom">
        </el-table-column>
        <el-table-column
          prop="taskName"
          label="任务名"
          sortable="custom"
          width="120"
        >
        </el-table-column>

        <el-table-column
          prop="taskRules"
          label="CRON"
          sortable="custom"
          width="120"
        >
          <template slot="header" slot-scope="">
            <el-tooltip
              class="item"
              effect="dark"
              content="Cron表达式"
              placement="top-start"
            >
              <span>CRON <i class="el-icon-question"></i></span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          prop="appName"
          label="所属应用"
          width="160"
          sortable="custom"
        >
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          sortable="custom"
          width="160"
        >
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          sortable="custom"
          width="160"
        >
        </el-table-column>
        <el-table-column
          label="状态"
          sortable="custom"
          prop="taskStatus"
          width="80"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.taskStatus == 1 ? 'success' : 'danger'">
              {{ scope.row.taskStatus == 1 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-popconfirm
              title="确定触发任务吗？"
              @confirm="handleRun(scope.$index, scope.row)"
            >
              <el-button slot="reference" type="primary" size="mini"
                >触发</el-button
              >
            </el-popconfirm>
            <el-button
              class="mr10 ml10"
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定删除吗？"
              @confirm="handleDelete(scope.$index, scope.row)"
            >
              <el-button slot="reference" type="danger" size="mini"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        layout="prev, pager, next"
        :total="page.total"
        :page-size="page.size"
        :page-count="page.total / page.size"
        :current-page.sync="page.current"
        class="mt10"
        @current-change="currentChange()"
      >
      </el-pagination>
    </div>
    <!-- 添加新的任务 -->
    <el-dialog title="新的任务" :visible.sync="dialogAdd">
      <el-form
        :model="newTask"
        :rules="rules"
        :label-width="formLabelWidth"
        ref="newTask"
      >
        <el-form-item label="任务名称" prop="taskName">
          <el-input
            v-model="newTask.taskName"
            autocomplete="off"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="CRON" prop="taskRules">
          <el-input
            v-model="newTask.taskRules"
            autocomplete="off"
            style="width: 300px"
            class="mr10"
          ></el-input>
          <el-tooltip
            class="item"
            effect="dark"
            content="Cron表达式生成，网址：https://www.bejson.com/othertools/cron/"
            placement="top-start"
          >
            <i class="el-icon-question"></i>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="所属应用" prop="appId">
          <el-select
            v-model="newTask.appId"
            filterable
            :filter-method="appFilter"
            clearable
          >
            <el-option
              v-for="item in appList"
              :key="item.appId"
              :label="item.appName"
              :value="item.appId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务状态" prop="taskStatus">
          <el-radio-group v-model="newTask.taskStatus" size="medium">
            <el-radio border :label="1">启用</el-radio>
            <el-radio border :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAdd = false">取 消</el-button>
        <el-button type="primary" @click="addTask()">保存</el-button>
      </div>
    </el-dialog>
    <!-- 编辑任务 -->
    <el-dialog title="编辑任务" :visible.sync="dialogEdit">
      <el-form
        :model="thisTask"
        :rules="rules"
        :label-width="formLabelWidth"
        ref="editTask"
      >
        <el-form-item label="任务名称" prop="taskName">
          <el-input
            v-model="thisTask.taskName"
            autocomplete="off"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="CRON" prop="taskRules">
          <el-input
            v-model="thisTask.taskRules"
            autocomplete="off"
            style="width: 300px"
            class="mr10"
          ></el-input
          ><el-tooltip
            class="item"
            effect="dark"
            content="Cron表达式生成，网址：https://www.bejson.com/othertools/cron/"
            placement="top-start"
          >
            <i class="el-icon-question"></i>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="所属应用" prop="appId">
          <el-select
            v-model="thisTask.appId"
            filterable
            :filter-method="appFilter"
            clearable
          >
            <el-option
              v-for="item in appList"
              :key="item.appId"
              :label="item.appName"
              :value="item.appId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务状态" prop="taskStatus">
          <el-radio-group v-model="thisTask.taskStatus" size="medium">
            <el-radio border :label="1">启动</el-radio>
            <el-radio border :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEdit = false">取 消</el-button>
        <el-button type="primary" @click="editTask()">更新</el-button>
      </div>
    </el-dialog>
  </div>
</template>

  <script>
import {
  listTask,
  deleteTask,
  batchDeleteTask,
  batchDisabledTask,
  batchEnabledTask,
  addTask,
  updateTask,
  listAppOfEnable,
  verifyCron,
  runTask,
} from "@/api/index";
export default {
  data() {
    var checkCron = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入任务执行规则"));
      }
      verifyCron({ data: { cron: value } }).then((res) => {
        console.log(res);
        if (res.data.data) {
          callback();
        } else {
          callback(new Error("Cron表达式有误"));
        }
      });
    };
    return {
      rules: {
        taskName: [
          { required: true, message: "请输入任务名称", trigger: "blur" },
        ],
        taskRules: [
          {
            validator: checkCron,
            required: true,
            trigger: "blur",
          },
        ],
        taskStatus: [
          { required: true, message: "请设置任务状态", trigger: "blur" },
        ],
        appId: [{ required: true, message: "请选择所属应用", trigger: "blur" }],
      },
      dialogAdd: false,
      dialogEdit: false,
      formLabelWidth: "120px",
      newTask: {
        taskName: "",
        taskStatus: 1,
      },
      thisTask: {
        taskName: "",
        taskStatus: 1,
      },
      defaultSearch: {
        taskName: "",
      },
      search: {
        taskName: "",
      },
      loading: true,
      page: {
        total: 0,
        size: 10,
        current: 1,
        records: [],
        orders: [
          {
            column: "update_time",
            asc: false,
          },
        ],
      },
      multipleSelection: [],
      appList: [],
      allAppList: [],
    };
  },
  methods: {
    //批量删除
    handlerBatchDeleteTask() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请先选择需要删除的任务",
          type: "warning",
        });
        return;
      }
      batchDeleteTask({
        data: this.multipleSelection.flatMap((item) => item.taskId),
      }).then((res) => {
        if (res == undefined || res == -1) {
          return;
        }
        console.log(res);
        this.$message({
          message: "批量删除成功",
          type: "success",
        });
        this.currentChange();
      });
    },
    //批量启用
    handlerEnabledApp() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请先选择需要启用的任务",
          type: "warning",
        });
        return;
      }
      batchEnabledTask({
        data: this.multipleSelection.flatMap((item) => item.taskId),
      }).then((res) => {
        if (res == undefined || res == -1 || res == 1) {
          return;
        }
        console.log(res);
        this.$message({
          message: "批量启用成功",
          type: "success",
        });
        this.currentChange();
      });
    },
    //批量禁用
    handlerDisabledTask() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请先选择需要禁用的任务",
          type: "warning",
        });
        return;
      }
      batchDisabledTask({
        data: this.multipleSelection.flatMap((item) => item.taskId),
      }).then((res) => {
        if (res == undefined || res == -1 || res == 1) {
          return;
        }
        console.log(res);
        this.$message({
          message: "批量禁用成功",
          type: "success",
        });
        this.currentChange();
      });
    },
    handlerSelectAppName(item, task) {
      console.log("handlerSelectAppName");
      task.appId = item.appId;
    },
    appFilter(query = "") {
      let arr = this.allAppList.filter((item) => {
        return item.appName.includes(query);
      });
      if (arr.length > 50) {
        this.appList = arr.slice(0, 50);
      } else {
        this.appList = arr;
      }
    },
    //获取app列表
    listApp() {
      listAppOfEnable().then((res) => {
        this.allAppList = res.data.data;
        this.appFilter();
      });
    },
    //选择
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //编辑任务
    editTask() {
      this.$refs.editTask.validate((valid) => {
        if (valid) {
          console.log("验证通过");

          let thisTask = Object.assign({}, this.thisTask);
          //过滤找到appName;
          let arr = this.allAppList.filter((item) => {
            return item.appId.includes(thisTask.appId);
          });
          thisTask.appName = arr[0].appName;
          thisTask.createTime = null;
          thisTask.updateTime = null;
          updateTask({ data: thisTask }).then((res) => {
            console.log(res);
            if (res == undefined || res == -1) return;
            this.$message({
              message: "更新成功",
              type: "success",
            });
            this.dialogEdit = false;
            this.currentChange();
          });
        } else {
          console.log("验证失败");
        }
      });
    },
    //添加新任务
    addTask() {
      this.$refs.newTask.validate((valid) => {
        if (valid) {
          console.log("验证通过");
          let newTask = Object.assign({}, this.newTask);
          //过滤找到appName;
          let arr = this.allAppList.filter((item) => {
            return item.appId.includes(newTask.appId);
          });
          newTask.appName = arr[0].appName;
          addTask({ data: newTask }).then((res) => {
            if (res == undefined || res == -1) return;
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.dialogAdd = false;
            this.currentChange();
          });
        } else {
          console.log("验证失败");
        }
      });
    },
    // 排序
    sortChange(e) {
      console.log(e);
      switch (e.prop) {
        case "taskId":
          this.page.orders[0] = {
            column: "task_id",
            asc: e.order == "ascending" || e.order == null ? true : false,
          };
          break;
        case "taskName":
          this.page.orders[0] = {
            column: "task_name",
            asc: e.order == "ascending" || e.order == null ? true : false,
          };
          break;
        case "createTime":
          this.page.orders[0] = {
            column: "create_time",
            asc: e.order == "ascending" || e.order == null ? true : false,
          };
          break;
        case "updateTime":
          this.page.orders[0] = {
            column: "update_time",
            asc: e.order == "ascending" || e.order == null ? true : false,
          };
          break;
        case "taskStatus":
          this.page.orders[0] = {
            column: "task_status",
            asc: e.order == "ascending" || e.order == null ? true : false,
          };
          break;
      }
      if (e.order == null) {
        this.page.orders[0] = {
          column: "update_time",
          asc: false,
        };
      }
      this.currentChange();
    },
    //刷新
    refresh() {
      this.search = Object.assign({}, this.defaultSearch);
      var that = this;
      this.currentChange(function () {
        that.$message({ message: "刷新成功", type: "success" });
      });
    },
    //换页
    currentChange(func) {
      console.log(this.page);
      var page = Object.assign({}, this.page);
      page.records = [this.search];
      this.listData(page, func);
    },
    //查询列表
    listData(page, func = function () {}) {
      listTask({ data: page }).then((res) => {
        console.log(res);
        if (res.data.code == 200) {
          this.page = res.data.data;
          func();
        }
        this.loading = false;
      });
    },
    //编辑
    handleEdit(index, row) {
      console.log(index, row);
      this.dialogEdit = true;
      this.thisTask = Object.assign({}, row);
    },
    //删除
    handleDelete(index, row) {
      console.log(index, row);
      deleteTask(row.taskId).then((res) => {
        console.log(res);
        if (res == undefined || res == -1) return;
        this.$message({
          message: "删除成功",
          type: "success",
        });
        this.currentChange();
      });
    },
    handleRun(index, row) {
      console.log(index, row);
      runTask(row.taskId).then((res) => {
        console.log(res);
        if (res == undefined || res == -1) return;
        this.$message({
          message: "触发成功",
          type: "success",
        });
        this.currentChange();
      });
    },
  },
  mounted() {
    this.loading = true;
    console.log("mounted");
    var page = Object.assign({}, this.page);
    page.records = [this.search];
    this.listData(page);
  },
  created() {
    this.listApp();
  },
};
</script>

<style scoped>
.mr10 {
  margin-right: 10px;
}
.ml10 {
  margin-left: 10px;
}
.mt10 {
  margin-top: 10px;
}
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}
.handle-input {
  width: 300px;
  display: inline-block;
}
</style>
